package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.JwtTool;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {
    @Resource
    private JwtTool jwtTool;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址薄
     *
     * @param dto     地址薄信息
     * @param request 请求对象
     */
    @Override
    public void addAddressBook(AddressBookUpsertReqDTO dto, HttpServletRequest request) {
        // userId
        String token = request.getHeader("Authorization");
        Long userId = jwtTool.parseToken(token).getId();
        // 经度，纬度
        String[] location = dto.getLocation().split(",");
        // 数据封装
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        addressBook.setUserId(userId);
        addressBook.setLon(Double.valueOf(location[0]));
        addressBook.setLat(Double.valueOf(location[1]));
        addressBook.setCreateTime(LocalDateTime.now());
        baseMapper.insert(addressBook);
    }

    /**
     * 分页查询地址薄
     *
     * @param dto 分页查询参数
     * @return List
     */
    @Override
    public PageResult<AddressBook> getPageAddress(AddressBookPageQueryReqDTO dto) {
        // 构建查询
        LambdaQueryChainWrapper<AddressBook> wrapper = lambdaQuery();
        if (dto.getIsAsc1()) {
            wrapper.orderByAsc(AddressBook::getIsDefault);
        } else if (dto.getIsAsc2()) {
            wrapper.orderByAsc(AddressBook::getCreateTime);
        } else {
            wrapper.orderByDesc(AddressBook::getIsDefault);
        }
        Page<AddressBook> page = wrapper.page(new Page<AddressBook>(dto.getPageNo(), dto.getPageSize()));
        PageResult<AddressBook> pageResult = new PageResult<>();
        pageResult.setPages(page.getPages());
        pageResult.setTotal(page.getTotal());
        pageResult.setList(page.getRecords());

        return pageResult;
    }

    /**
     * 编辑地址薄数据
     *
     * @param id  id
     * @param dto 地址薄数据
     */
    @Override
    public void updateAddressBook(Long id, AddressBookUpsertReqDTO dto) {
        if (ObjectUtils.isNull(id)) {
            throw new ForbiddenOperationException("数据传输异常");
        }

        // 封装数据
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        addressBook.setId(id);
        addressBook.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(addressBook);
    }

    /**
     * 设置/取消默认地址
     *
     * @param id   id
     * @param flag 是否默认
     */
    @Override
    public void yNDefault(Long id, Integer flag) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        // 取消默认地址
        if (flag == 0) {
            addressBook.setIsDefault(flag);
            baseMapper.updateById(addressBook);
            return;
        }
        // 设置默认地址
        // 将旧的默认地址给清除
        lambdaUpdate()
                .eq(AddressBook::getIsDefault, 1)
                .set(AddressBook::getIsDefault, 0)
                .set(AddressBook::getUpdateTime, LocalDateTime.now())
                .update();
        addressBook.setIsDefault(flag);
        baseMapper.updateById(addressBook);
    }
}
